package com.micro.platform.starter.config;

import com.micro.platform.starter.config.loadbalance.rest.HeaderInterceptor;
import com.micro.platform.starter.config.loadbalance.rest.RestLoadBalancerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.loadbalancer.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Configuration
@ConditionalOnClass(RestTemplate.class)
public class RestTemplateConfig {

    @Value("${dubbo.registry.version:}")
    private String version;

    @Autowired
    private ApplicationContext applicationContext;

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public RestTemplateCustomizer restTemplateCustomizer(LoadBalancerClient loadBalancerClient, LoadBalancerRequestFactory requestFactory) {
        RestLoadBalancerInterceptor restLoadBalancerInterceptor = new RestLoadBalancerInterceptor(loadBalancerClient, requestFactory, version);
//        HeaderInterceptor headerInterceptor = new HeaderInterceptor(applicationContext);
        return restTemplate -> {
            List<ClientHttpRequestInterceptor> list = new ArrayList<>(restTemplate.getInterceptors());
//            list.add(headerInterceptor);
            list.add(restLoadBalancerInterceptor);
            restTemplate.setInterceptors(list);
        };
    }
}
